package com.cdu.util;


import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: easy-help-v2
 * @description:
 * @author: hanabi
 * @create: 2022-05-19 11:29
 **/

public class ParamUtil {
    public static Map<String, Object> getAllParamMap(HttpServletRequest request) {

        Map<String, Object> hashMap = new HashMap();
        Enumeration enums = request.getParameterNames();
        String paramName = null;
        String paramValue = null;

        //先读取form格式，如果读取不到就读取json格式
        while (enums.hasMoreElements()) {
            paramName = (String) enums.nextElement();
            paramValue = (String) request.getParameter(paramName);
            if (paramValue != null && !"".equals(paramValue)) {
                hashMap.put(paramName, paramValue);
            }
        }
        //读取json
        if (hashMap == null || hashMap.size() == 0) {

            BufferedReader streamReader = null;
            StringBuilder responseStrBuilder = new StringBuilder();
            try {
                streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

                String inputStr;
                while ((inputStr = streamReader.readLine()) != null)
                    responseStrBuilder.append(inputStr);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject;
            if (responseStrBuilder == null || responseStrBuilder.length() == 0) {
                jsonObject = new JSONObject();
            } else {
                jsonObject = JSONObject.fromObject(responseStrBuilder.toString());
            }

            hashMap = jsonObject;
        }
        return hashMap;
    }

}
